package com.manor.im.activity

import android.content.Context
import android.content.Intent
import android.graphics.Bitmap
import android.graphics.Color
import android.graphics.drawable.Drawable
import android.view.View
import com.alibaba.android.arouter.facade.annotation.Route
import com.alibaba.fastjson.JSON
import com.bumptech.glide.Glide
import com.bumptech.glide.request.target.CustomTarget
import com.bumptech.glide.request.transition.Transition
import com.gyf.immersionbar.ImmersionBar
import com.orhanobut.logger.Logger
import com.manor.common.CommonAppConfig
import com.manor.common.Constants
import com.manor.common.activity.AbsActivity
import com.manor.common.bean.ChatAnchorParam
import com.manor.common.bean.ChatAudienceParam
import com.manor.common.bean.ChatReceiveGiftBean
import com.manor.common.custom.blur.Blurred
import com.manor.common.event.GiftShowEvent
import com.manor.common.http.HttpCallback
import com.manor.common.http.PitUtil
import com.manor.common.presenter.GiftAnimViewHolder
import com.manor.im.R
import com.manor.im.dialog.ChatGiftDialog
import com.manor.im.helper.ChatLayoutHelper
import com.manor.im.http.ImHttpUtil
import com.tencent.imsdk.v2.V2TIMConversation
import com.tencent.qcloud.tim.uikit.component.AudioPlayer
import com.manor.common.bean.ChatInfo
import com.manor.common.utils.ClickUtil
import com.manor.common.utils.RouteUtil
import com.manor.common.utils.ToastUtil
import com.manor.common.interfaces.CommonCallback
import com.manor.common.utils.*
import com.tencent.qcloud.tim.uikit.base.IUIKitCallBack
import com.tencent.qcloud.tim.uikit.bean.ChatBgEvent
import com.tencent.qcloud.tim.uikit.modules.chat.layout.input.InputLayout
import com.tencent.qcloud.tim.uikit.modules.chat.layout.message.MessageLayout
import com.tencent.qcloud.tim.uikit.modules.message.MessageInfo
import com.tencent.qcloud.tim.uikit.modules.message.MessageInfoUtil
import kotlinx.android.synthetic.main.activity_h_chat.*
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode

/**
 *
 * @date  2020/7/2  11:47
 * @version 1.0
 */
class HChatRoomActivity : AbsActivity(), InputLayout.ChatCallHandler, ChatGiftDialog.ActionListener {

    private var mChatType = Constants.CHAT_TYPE_NONE.toInt()
    private var avatar = ""
    private var mGiftAnimViewHolder: GiftAnimViewHolder? = null

    companion object {

         fun forward(context: Context, userId: String? = "", chatName: String? = "", avatar: String? = "",
                            type: Int = V2TIMConversation.V2TIM_C2C) {
            if (context == null)
                return
            val chatInfo = ChatInfo()
            chatInfo.type = if (type == V2TIMConversation.V2TIM_GROUP) V2TIMConversation.V2TIM_GROUP else V2TIMConversation.V2TIM_C2C
            chatInfo.id = userId
            chatInfo.chatName = chatName
            forward(context, avatar?:"", chatInfo)
        }

        fun forward(context: Context, avatar: String, chatInfo: ChatInfo) {
            if (context == null)
                return
            val intent = Intent(context, HChatRoomActivity::class.java)
            intent.putExtra(Constants.CHAT_INFO, chatInfo)
            intent.putExtra(Constants.URL, avatar)
            context.startActivity(intent)

        }


    }


    override fun getLayoutId(): Int = R.layout.activity_h_chat


    override fun main() {
        super.main()
        ImmersionBar.with(this).transparentStatusBar().init()
//        Blurred.init(this@HChatRoomActivity)

        onLoadIntent(intent)

        EventBus.getDefault().register(this)

        MessageInfoUtil.setOpenChatActivity(true)
    }

    override fun onNewIntent(intent: Intent?) {
        super.onNewIntent(intent)
        onLoadIntent(intent)
    }

    private fun onLoadIntent(intentX: Intent?){
        avatar = intentX?.getStringExtra(Constants.URL) ?: ""

        val chatInfo: ChatInfo? = intentX?.getSerializableExtra(Constants.CHAT_INFO) as ChatInfo?



        chatInfo?.run {
            //测试的是administrator
            if (id == Constants.IM_MSG_ADMIN || id == "administrator") {
                chatLayout.inputLayout.visibility = View.GONE
            }

        }
        KLog.e("HChatRoomActivity", " ${chatInfo?.toString()}")

        chatLayout.chatInfo = chatInfo

        chatLayout.titleBar.rightGroup.visibility = View.INVISIBLE
        chatLayout.titleBar.setBackgroundColor(Color.WHITE)
        chatLayout.initDefault()
        chatLayout.inputLayout.setChatCallHandler(this)
        chatLayout.messageLayout.onItemClickListener = itemClickListener

        //  通过api设置ChatLayout各种属性的样例
        val helper = ChatLayoutHelper(mContext)
        helper.customizeChatLayout(chatLayout, chatInfo?.type == V2TIMConversation.V2TIM_GROUP)

//        initBlur()
    }


    override fun onPause() {
        super.onPause()
        AudioPlayer.getInstance().stopPlay()
    }

    override fun onDestroy() {
        KLog.e("HChatRoom#onDestroy", "onDestroy---------------------")
        onRelease()
        super.onDestroy()
    }

    override fun onBackPressed() {
        onRelease()
        super.onBackPressed()
    }

    private fun onRelease(){
        EventBus.getDefault().unregister(this)
        MessageInfoUtil.setOpenChatActivity(false)
        mGiftAnimViewHolder?.release()
        mGiftAnimViewHolder = null
        if (chatLayout != null) {
            chatLayout.exitChat()
        }
    }


    private fun initBlur() {

        val bgUrl = if (StringUtil.isNotEmpty(CommonAppConfig.getInstance().chatBg))
            CommonAppConfig.getInstance().chatBg
        else
            avatar

        if (mContext!=null && !isFinishing && !isDestroyed) {
            Glide.with(mContext)
                    .asBitmap()
                    .load(bgUrl)
                    .into(customTarget)
        }
    }

    private val customTarget = object : CustomTarget<Bitmap>() {
        override fun onLoadCleared(placeholder: Drawable?) {
        }

        override fun onResourceReady(resource: Bitmap, transition: Transition<in Bitmap>?) {
            if (!isFinishing && !isDestroyed && !Blurred.isNull()) {
                val bp: Bitmap? = Blurred().startDefault(resource)
                bp?.let {
                    chatLayout.titleBar.background = null
                    chatLayout.chatBackGround.setImageBitmap(it)
                }

            }
        }


    }



    private val itemClickListener = object : MessageLayout.OnItemClickListener {
        override fun onMessageLongClick(view: View?, position: Int, messageInfo: MessageInfo?) {
            messageInfo?.run {
                if (fromUser == Constants.IM_MSG_ADMIN || fromUser == "administrator"){
                    //私人秘书
                }else {
                    chatLayout.messageLayout.showItemPopMenu(position - 1, this, view)
                }
            }

        }

        override fun onUserIconClick(view: View?, position: Int, messageInfo: MessageInfo?) {
            messageInfo?.run {
                if (fromUser == Constants.IM_MSG_ADMIN || fromUser == "administrator")
                    return@run

                if (chatLayout.chatInfo.type == V2TIMConversation.V2TIM_C2C) {
                    if (ClickUtil.canClick())
                        RouteUtil.forwardUserHome(this.fromUser)
                }
            }
        }

    }


    private fun loadChatBg() {
        if (StringUtil.isEmpty(CommonAppConfig.getInstance().chatBg)) {
            ImHttpUtil.getIMChatBg(CommonAppConfig.getInstance().uid, object : HttpCallback() {
                override fun onSuccess(code: Int, msg: String?, info: String?) {
                    if (code == 0 && info != null && info.isNotEmpty()) {
                        val bg = JSON.parseObject(info)?.getString("background")
                        CommonAppConfig.getInstance().chatBg = bg
                        initBlur()
                    }
                }

            })
        }
    }


    private fun showGift(giftBean: ChatReceiveGiftBean?) {
        if (mGiftAnimViewHolder == null) {
            mGiftAnimViewHolder = GiftAnimViewHolder(mContext, rootLay)
            mGiftAnimViewHolder?.addToParent()
        }
        mGiftAnimViewHolder?.showGiftAnim(giftBean)

    }

    override fun onChatVideoCall() {
        mChatType = Constants.CHAT_TYPE_VIDEO.toInt()
        checkChatStatus()
    }

    override fun onChatAudioCall() {
        mChatType = Constants.CHAT_TYPE_VOICE.toInt()
        checkChatStatus()
    }

    override fun onChatGiftSend() {
        if (chatLayout.chatInfo.type == V2TIMConversation.V2TIM_GROUP) {
                ChatGiftDialog.forward(supportFragmentManager, "", isGuard = false, isFromGroup = true, showId = "0",
                        groupId = chatLayout.chatInfo.id.toString(), listener = this@HChatRoomActivity)
        } else {
            ChatGiftDialog.forward(supportFragmentManager, chatLayout.chatInfo.id.toString(), false,
                    "0", this@HChatRoomActivity)
        }

    }

    override fun onChargeClick() {
        RouteUtil.forwardPath(RouteUtil.PC_WEB, StaIntentUtil.QUICK_RECHARGE)
    }


    override fun onGiftSend(info: String, call: CommonCallback<Boolean>) {
        val msgInfo = MessageInfoUtil.buildCustomMessage(info)
        chatLayout.chatManager.sendMessage(msgInfo, false, object : IUIKitCallBack {
            override fun onSuccess(data: Any?) {

                call.callback(true)
            }

            override fun onError(module: String?, errCode: Int, errMsg: String?) {
            }
        })
    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onNewShowGift(e: GiftShowEvent) {
        if (!isFinishing)
            if (e.giftBean.isLocal) {
                showGift(e.giftBean)
            } else {
                if (e.giftBean?.group_id!="0"&&StringUtil.isNotEmpty(e.giftBean?.group_id)){
                    if (e.giftBean?.group_id == chatLayout.chatInfo.id)
                        showGift(e.giftBean)
                }else{
                    if (e.giftBean?.uid == chatLayout.chatInfo.id)
                        showGift(e.giftBean)
                }

            }

    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onChatBgChange(e: ChatBgEvent?) {
        if (e?.needRefresh == true) {
//            loadChatBg()
        }
    }


    private fun checkChatStatus() {
        //腾讯IM: 自定义消息---> {"action":2,"level_anchor":1,"method":"call","showid":"1586309146","total":"10","type":2}
        ImHttpUtil.checkChatStatus(chatLayout.chatInfo.id, object : HttpCallback() {
            override fun onSuccess(code: Int, msg: String, info: String) {
                Logger.e("checkChatStatus info == " + info)
                if (code == 0 && info.isNotEmpty()) {
                    val result: String = PitUtil.strGetFirst(info)

                    val obj = JSON.parseObject(result)
                    if (obj.getIntValue("status") == 1) { //1主播邀用户
                        chatAncToAudStart()
                    } else { //0用户邀主播
                        chatAudToAncStart()
                    }
                } else {
                    ToastUtil.show(msg)
                }
            }
        })
    }

    /**
     * 观众向主播发起通话邀请，检测主播状态，同时获取自己的推拉流地址
     */
    fun chatAudToAncStart() {
        ImHttpUtil.chatAudToAncStart(chatLayout.chatInfo.id, mChatType, object : HttpCallback() {
            override fun onSuccess(code: Int, msg: String, info: String) {
                if (code == 0) {
                    if (info.isNotEmpty()) {
                        val result = PitUtil.strGetFirst(info)

                        val obj = JSON.parseObject(result)
                        val param = ChatAudienceParam()
                        param.anchorID = chatLayout.chatInfo.id
                        param.anchorName = chatLayout.chatInfo.chatName
                        param.anchorAvatar = avatar
                        //param.anchorLevel = mToUserBean.getLevelAnchor()
                        param.sessionId = obj.getString("showid")
                        param.audiencePlayUrl = obj.getString("pull")
                        param.audiencePushUrl = obj.getString("push")
                        param.anchorPrice = obj.getString("total")
                        param.chatType = obj.getIntValue("type")
                        param.roomId = obj.getString("roomid")
                        param.userSign = obj.getString("UserSig")
                        param.isAudienceActive = true
                        Logger.e("chatAudToAncStart roomid=" + param.roomId + ",UserSig=" + param.userSign)
                        RouteUtil.forwardAudienceActivity(param)
                    }
                } else {
                    ToastUtil.show(msg)
                }
            }
        })
    }


    /**
     * 主播向观众发起通话邀请，检测观众状态，同时获取自己的推拉流地址
     */
    fun chatAncToAudStart() {
        ImHttpUtil.chatAncToAudStart2(chatLayout.chatInfo.id, mChatType, object : HttpCallback() {
            override fun onSuccess(code: Int, msg: String, info: String) {
                if (code == 0) {
                    if (info.isNotEmpty()) {
                        val obj = JSON.parseObject(info)
                        val param = ChatAnchorParam()
                        param.audienceID = chatLayout.chatInfo.id
                        param.audienceName = chatLayout.chatInfo.chatName
                        param.audienceAvatar = avatar
                        param.sessionId = obj.getString("showid")
                        param.anchorPlayUrl = obj.getString("pull")
                        param.anchorPushUrl = obj.getString("push")
                        param.price = obj.getString("total")
                        param.chatType = obj.getIntValue("type")
                        param.isAnchorActive = true
                        RouteUtil.forwardAnchorActivity(param)
                    }
                } else {
                    ToastUtil.show(msg)
                }
            }
        })
    }


}